import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const usePageButtonStore = defineStore('pageButton', () => {
  const pageButtonList = ref([]);
  const loading = ref(false);

  const setList = (list) => {
    if (!list) return;
    pageButtonList.value = list || [];
  };

  const getList = async() => {
    if (pageButtonList.value && pageButtonList.value.length > 0) {
      return pageButtonList.value || [];
    }

    if (loading.value) {
      await sleep(100);
      return await getList();
    }

    loading.value = true;
    try {
      const res = await api.post('/business/page-button/list');
      loading.value = false;
      setList(res.data);
      return pageButtonList.value || [];
    } finally {
      loading.value = false;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  const clearData = () => {
    pageButtonList.value = [];
  };

  return { getList, clearData };
});
